import {getStyle} from "@/components/manfigy/directive/tools";

export default {
    mounted(element) {
        //获取元素
        const oImgWrap = element,
            oMagWrap = oImgWrap.querySelector('.mag-wrap'),
            oMagImg = oImgWrap.querySelector('.mag-img'),
            ImgWidth = getStyle(oMagImg, 'width'),
            ImgHeight = getStyle(oMagImg, 'height'),
            magWidth = getStyle(oMagWrap, 'width'),
            magHeight = getStyle(oMagWrap, 'height'),
            //获取容器距离左边及上边的距离
            imgX = oImgWrap.offsetLeft,
            imgY = oImgWrap.offsetTop;
        const init = () => {
            bindEvent();
        }

        function bindEvent() {
            //鼠标进入的事件
            oImgWrap.addEventListener('mouseover', function (e) {
                oMagWrap.className += ' show';

                showMag(getXY(e).x,getXY(e).y);
                console.log(getXY(e).x)
                document.addEventListener('mousemove',handlerMouseMove,false);
            }, false)
            //鼠标移除的事件
            oImgWrap.addEventListener('mouseout', handlerMouseOut, false)
        }

        function handlerMouseMove(e) {
            console.log(111);
            const {x,y,mouseX,mouseY} = getXY(e);
            showMag(x,y,mouseX,mouseY);
            if (mouseX <0 || mouseY < 0 ||
                mouseX >ImgWidth || mouseY > ImgHeight
            ) {
                oMagWrap.className = 'mag-wrap';
                document.removeEventListener('mousemove',handlerMouseMove,false);
            }

        }

        function handlerMouseOut(e) {
            oMagWrap.className = 'mag-wrap';
            document.removeEventListener('mousemove',handlerMouseMove,false);
        }

        function showMag(x,y,mouseX,mouseY) {
            oMagWrap.style.left = x + 'px';
            oMagWrap.style.top = y + 'px';
            oMagImg.style.left = -x +'px';
            oMagImg.style.top = -y + 'px';
        }

        function getXY(e){
            return {
                x:e.pageX - imgX - magWidth/2,
                y:e.pageY - imgY - magHeight/2,
                mouseX:e.pageX - imgX,
                mouseY:e.pageY - imgY
            }
        }
        init();

    }
}